package com.ssm.start;

import com.ssm.start.util.TomcatUtil;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;

import java.net.URL;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public class StartMain {


    private final static String WEB_CONTEXT = "/FIVE-SSM-TOMCAT" ;

    public static void main(String []args) throws LifecycleException {
        Tomcat tomcat = new Tomcat();
        URL resource = Thread.currentThread().getContextClassLoader().getResource("");
        Context webApp = tomcat.addWebapp(WEB_CONTEXT, Objects.nonNull(resource) ? resource.getPath() : null);
        setPortIp(tomcat,webApp);
        //see web.xml
        Map<String,String> initParams = new LinkedHashMap<>();
        initParams.put("contextConfigLocation","classpath:spring/spring.xml");
        TomcatUtil.addContextParam(webApp,initParams);
        initParams.clear();

        TomcatUtil.addListener(webApp,"org.springframework.web.context.ContextLoaderListener");
        TomcatUtil.addListener(webApp,"com.ssm.comm.eureka.EurekaListener");

        /**
         * 拦截器拦截路径自己diy吧
         */
        TomcatUtil.addFilter(webApp,"com.ssm.comm.session.ShareSessionFilter","ShareSessionFilter",
               "分布式session过滤器",Arrays.asList("/*"),initParams) ;

        initParams.put("encoding","UTF-8");
        TomcatUtil.addFilter(webApp,"org.springframework.web.filter.CharacterEncodingFilter",
                "encodingFilter", "char encoding filter", Arrays.asList("/*"),initParams);
        initParams.clear();

        initParams.put("contextConfigLocation","classpath:spring/spring-web.xml");
        TomcatUtil.addServlet(webApp,"SpringDispatcherServlet",
                "org.springframework.web.servlet.DispatcherServlet",initParams,Arrays.asList("/*"),
                1);



        TomcatUtil.startTomcat(tomcat);
    }

    public static  void setPortIp(Tomcat tomcat,Context webApp){
        //构建Connector对象,此对象负责与客户端的连接.
        Connector con=new Connector("HTTP/1.1");
            //设置服务端的监听端口
         con.setPort(8087);
         tomcat.getService().addConnector(con);

    }
}
